<?php namespace App\Controllers;

use \App\App;

class Rank extends App
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $rankings = $this->db->table("rankApi")
            ->get()
            ->result();
        $categoryModel = new \App\Models\Category();
        $this->view->categories = $categoryModel->where(['parent' => 0])->findAll();

        $this->view->ranks = $rankings;
        $this->view->viewTitle = "排行榜";
        $this->render("/front/rank/rank", "/front/header");
    }

    public function get($id = null)
    {
        $page = $this->request->request("page") ?: 0;

        if ($id) {
            $api = new \App\Models\Api(1);
            $rank = $api->getUrl('rank', ["sp" => $id]);
            $stories = $rank['ranking']['books'];
            $this->view->staticUrl = $api->getUrl("static", "", false);
            $this->view->type = "cloud";
        } else {
            $storyModel = new \App\Models\Story();
            $stories = $storyModel->order("vote", "DESC")->findAll(20, $page * 20);
            $this->view->type = "local";
        }

        $this->view->page = $page;
        $this->view->stories = $stories;
        $this->render("/front/rank/list", "/front/header");
    }
}